package zzj.campus_book_sharing_platform.test;

import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class FileUtil {
    /**
     * word转pdf
     *
     * @param inputFile  word文档
     * @param outputFile pdf文档
     * @throws IOException
     */
    public static void wordToPdf(File inputFile, File outputFile) throws IOException {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            log.info("license.xml 文件失效");
            return;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            os = new FileOutputStream(outputFile);

            //解决乱码
            //如果是windows执行，不需要加这个
            //TODO 如果是linux执行，需要添加这个*****
            FontSettings.setFontsFolder("/usr/share/fonts/windows"+File.separator, true);

            Document doc = new Document(inputFile.getPath());
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
            os.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), (Object) e.getStackTrace());
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 验证License 若不验证则转化出的pdf文档会有水印产生
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = FileUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return result;
    }
}
